package com.sky.server.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SqlException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.pojo.StatusUpdate;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.server.DishServer;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServerImpl implements DishServer {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;


    // 分页查询
    @Override
    public PageResult pageEmployee(DishPageQueryDTO queryDTO) {
        // 查取所有分页
        List<DishVO> list = dishMapper.list();

        // 过滤条件
        // 如果有指定查询名称
        if (queryDTO.getName() != null) {
            list = list.stream().filter(category -> category.getName().contains(queryDTO.getName())).collect(Collectors.toList());
        }
        // 如果有指定菜品状态
        if (queryDTO.getStatus() != null) {
            list = list.stream().filter(category -> category.getStatus().equals(queryDTO.getStatus())).collect(Collectors.toList());
        }
        // 如果有指定菜品分类id
        if (queryDTO.getCategoryId() != null) {
            list = list.stream().filter(category -> {
                return category.getCategoryId() == (long) queryDTO.getCategoryId();
            }).collect(Collectors.toList());
        }
        // 进行分页与统计
        Long count = (long) list.size();
        list = list.stream().skip(((queryDTO.getPage() - 1) * queryDTO.getPageSize())).limit(queryDTO.getPageSize()).collect(Collectors.toList());

        PageResult pageResult = new PageResult();
        pageResult.setTotal(count);
        pageResult.setRecords(list);
        return pageResult;
    }

    // 根据id查菜品
    @Override
    public DishVO getById(Long id) {
        // 查询菜品信息
        DishVO dishVO = dishMapper.getById(id);
        // 查询口味信息
        List<DishFlavor> flavorList = dishFlavorMapper.getByIdWithFlavors(id);
        dishVO.setFlavors(flavorList);
        return dishVO;
    }

    // 新增菜品
    @Override
    @Transactional
    public void addDish(DishDTO requestDTO) {
        try {
            // 新增菜品后获取id
            Dish dish = new Dish();
            BeanUtil.copyProperties(requestDTO, dish);
            dishMapper.addDish(dish);

            // 获取口味列表，添加多个口味表
            List<DishFlavor> flavors = requestDTO.getFlavors();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
                dishFlavorMapper.addFlavor(flavor);
            }
        } catch (Exception e) {
            throw new SqlException("添加菜品错误");
        }
    }

    // 根据分类id查询dish列表
    @Override
    public List<DishVO> listByCategoryId(Integer categoryId) {
        List<Dish> dishList = dishMapper.listByCategoryId(categoryId);

        return dishList.stream().map(dish -> {
            DishVO dishVO = new DishVO();
            List<DishFlavor> flavors = dishFlavorMapper.getByIdWithFlavors(dish.getId());
            BeanUtil.copyProperties(dish, dishVO);
            dishVO.setFlavors(flavors);
            return dishVO;
        }).collect(Collectors.toList());
    }

    // 更新dish数据
    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
        // 更新dish表数据
        Dish dish = new Dish();
        BeanUtil.copyProperties(dishDTO, dish);
        try {
            dishMapper.update(dish);
        } catch (Exception e) {
            throw new SqlException("dish修改错误");
        }

        // 删除口味表信息，然后再次添加
        try {
            dishMapper.deleteByDish(dishDTO.getId());
            List<DishFlavor> flavors = dishDTO.getFlavors();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDTO.getId());
                dishFlavorMapper.addFlavor(flavor);
            }
        } catch (Exception e) {
            throw new SqlException("口味表修改失败");
        }
    }

    // 修改dish状态
    @Override
    @Transactional
    public void status(Dish dish) {
        try {
            dishMapper.update(dish);
            if (dish.getStatus() == 0) {
                // 菜品停售，相关套餐也要停售
                List<Long> setmealIds = setmealDishMapper.getSetmealByDishId(dish.getId());
                if (setmealIds != null && setmealIds.size() > 0) {
                    for (Long setmealId : setmealIds) {
                        // 将整个套餐都停了
                        Setmeal setmeal = new Setmeal();
                        setmeal.setStatus(0);
                        setmeal.setId(setmealId);
                        setmealMapper.update(setmeal);
                    }
                }
            }
        } catch (Exception e) {
            throw new SqlException("状态修改错误");
        }
    }

    // 批量删除根据id
    @Override
    public void deleteByIds(Long[] ids) {
        // 菜品是否起售
        for (Long id : ids) {
            DishVO dish = dishMapper.getById(id);
            if (dish.getStatus() == 1) {
                // 当前菜品处于起售中，不能删除
                log.info("菜品起售中");
                throw new BaseException("无法删除");
            }
        }
        List<Long> setmealIds = setmealMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            // 当前菜品被套餐关联了，不能删除
            log.info("当前菜品被套餐关联了");
            throw new BaseException("无法删除");
        }
        // 删除菜品表中的菜品数据
        for (Long id : ids) {
            try {
                dishMapper.deleteById(id);
                // 删除菜品关联的口味数据
                dishFlavorMapper.deleteByDishId(id);
            } catch (Exception e) {
                log.info("表数据删除失败");
                throw new BaseException("删除失败");
            }
        }
    }

    // 根据分类查取菜品
    @Override
    public List<Dish> getDishListByCategoryId(Long categoryId) {
        List<Dish> dishList = dishMapper.listByCategoryId(Math.toIntExact(categoryId));
        return dishList;
    }
}
